package pers.karl.web.converter;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.util.Date;

/**
 * @author karl
 * @description: 自定义日期转换器
 * @create 2019-05-15 00:59
 */
public class CustomDateConverter implements Converter<String, Date> {

    private String[] patterns;

    public void setPatterns(String[] patterns) {
        this.patterns = patterns;
    }

    @Override
    public Date convert(String s) {

        if (StringUtils.isBlank(s)) {
            throw new IllegalArgumentException(s + " must not be empty");
        }

        try {
            return DateUtils.parseDate(s, this.patterns);
        } catch (ParseException e) {
            throw new IllegalArgumentException(s + " is not valid date string");
        }

    }
}
